#!/bin/bash
# 应用镜像统一更新脚本
# 用途：同时更新Web服务(Deployment)和定时任务(CronJob)的镜像版本
# 使用场景：手动部署流程，镜像已通过scp上传并导入

set -euo pipefail

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 参数检查
if [ $# -lt 1 ]; then
    echo -e "${RED}错误：缺少镜像标签参数${NC}"
    echo ""
    echo "用法: $0 <镜像标签> [选项]"
    echo ""
    echo "选项:"
    echo "  --test              更新后立即测试CronJob"
    echo "  --cronjob-only      仅更新CronJob，不重启Deployment"
    echo "  --deployment-only   仅重启Deployment，不更新CronJob"
    echo ""
    echo "示例:"
    echo "  $0 latest                      # 更新Deployment和CronJob到latest"
    echo "  $0 1.0.1                       # 更新到指定版本"
    echo "  $0 latest --test               # 更新并测试"
    echo "  $0 latest --cronjob-only       # 仅更新CronJob"
    exit 1
fi

IMAGE_TAG=$1
TEST_MODE=false
CRONJOB_ONLY=false
DEPLOYMENT_ONLY=false

# 解析参数
shift
while [ $# -gt 0 ]; do
    case "$1" in
        --test)
            TEST_MODE=true
            ;;
        --cronjob-only)
            CRONJOB_ONLY=true
            ;;
        --deployment-only)
            DEPLOYMENT_ONLY=true
            ;;
        *)
            echo -e "${RED}未知参数: $1${NC}"
            exit 1
            ;;
    esac
    shift
done

# 参数冲突检查
if [ "$CRONJOB_ONLY" == "true" ] && [ "$DEPLOYMENT_ONLY" == "true" ]; then
    echo -e "${RED}错误：--cronjob-only 和 --deployment-only 不能同时使用${NC}"
    exit 1
fi

# 支持两种镜像格式：
# 1. localhost/python-app:1.0.0 （实际部署格式）
# 2. python-app:latest （兼容旧格式）
if [[ "${IMAGE_TAG}" == *":"* ]]; then
    # 已经包含完整镜像名和标签（如 localhost/python-app:1.0.0）
    IMAGE_NAME="${IMAGE_TAG}"
else
    # 仅有标签，自动添加前缀（如 1.0.0 -> localhost/python-app:1.0.0）
    IMAGE_NAME="localhost/python-app:${IMAGE_TAG}"
fi

echo "=========================================="
echo "  应用镜像统一更新工具"
echo "=========================================="
echo ""
echo "目标镜像: ${IMAGE_NAME}"
if [ "$CRONJOB_ONLY" == "true" ]; then
    echo "更新范围: 仅CronJob定时任务"
elif [ "$DEPLOYMENT_ONLY" == "true" ]; then
    echo "更新范围: 仅Deployment Web服务"
else
    echo "更新范围: Deployment + CronJob（全部）"
fi
echo ""

# 提示：镜像应该在 Worker 节点导入
# Master 节点只负责执行 kubectl 命令，不需要导入镜像
echo -e "${YELLOW}⚠️  注意：请确保镜像已在 Worker 节点导入${NC}"
if [[ "${IMAGE_NAME}" == localhost/* ]]; then
    VERSION="${IMAGE_NAME##*:}"
    echo "   Worker 节点执行: ssh root@172.16.0.121 'k3s ctr images import /tmp/python-app-${VERSION}.tar'"
else
    echo "   Worker 节点执行: ssh root@172.16.0.121 'k3s ctr images import /tmp/python-app-${IMAGE_TAG}.tar'"
fi
echo "   如果镜像未导入，Pod 将无法启动（ImagePullBackOff）"
echo ""

# ========== 更新Deployment（Web服务）==========
if [ "$CRONJOB_ONLY" != "true" ]; then
    echo "========== 更新 Deployment/python-app =========="

    # 检查 Deployment 是否存在
    if ! kubectl get deployment python-app -n default &>/dev/null; then
        echo -e "${YELLOW}⚠️  Deployment/python-app 不存在，跳过 Deployment 更新${NC}"
        echo ""
    else
        # 更新镜像标签
        echo "更新Deployment镜像标签到 ${IMAGE_NAME}..."
        kubectl set image deployment/python-app \
          python-app=${IMAGE_NAME} \
          -n default

        if [ $? -ne 0 ]; then
            echo -e "${RED}❌ Deployment镜像标签更新失败${NC}"
            exit 1
        fi
        echo -e "${GREEN}✅ Deployment镜像标签已更新${NC}"

        # 重启Deployment（强制拉取新镜像）
        echo "重启Deployment以应用新镜像..."
        kubectl rollout restart deployment/python-app -n default

        if [ $? -eq 0 ]; then
            echo -e "${GREEN}✅ Deployment已触发重启${NC}"

            # 等待Deployment就绪
            echo "等待Deployment就绪..."
            kubectl rollout status deployment/python-app -n default --timeout=120s

            if [ $? -eq 0 ]; then
                echo -e "${GREEN}✅ Deployment重启完成${NC}"
            else
                echo -e "${YELLOW}⚠️  Deployment重启超时，请手动检查${NC}"
            fi
        else
            echo -e "${RED}❌ Deployment重启失败${NC}"
            exit 1
        fi
        echo ""
    fi
fi

# ========== 更新CronJob（定时任务）==========
if [ "$DEPLOYMENT_ONLY" != "true" ]; then
    echo "========== 更新 CronJob/device-offline-monitor =========="
    kubectl set image cronjob/device-offline-monitor \
      offline-monitor=${IMAGE_NAME} \
      -n tasks

    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ device-offline-monitor 镜像已更新${NC}"
    else
        echo -e "${RED}❌ device-offline-monitor 更新失败${NC}"
        exit 1
    fi
    echo ""

    echo "========== 更新 CronJob/daily-tasks =========="
    kubectl set image cronjob/daily-tasks \
      daily-tasks=${IMAGE_NAME} \
      -n tasks

    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ daily-tasks 镜像已更新${NC}"
    else
        echo -e "${RED}❌ daily-tasks 更新失败${NC}"
        exit 1
    fi
    echo ""
fi

# 验证更新
echo "========== 验证更新 =========="

if [ "$CRONJOB_ONLY" != "true" ]; then
    echo "Deployment/python-app 当前镜像:"
    kubectl get deployment -n default python-app \
      -o jsonpath='{.spec.template.spec.containers[0].image}'
    echo ""

    echo "Deployment/python-app Pod状态:"
    kubectl get pods -n default -l app=python-app
    echo ""
fi

if [ "$DEPLOYMENT_ONLY" != "true" ]; then
    echo "CronJob/device-offline-monitor 当前镜像:"
    kubectl get cronjob -n tasks device-offline-monitor \
      -o jsonpath='{.spec.jobTemplate.spec.template.spec.containers[0].image}'
    echo ""

    echo "CronJob/daily-tasks 当前镜像:"
    kubectl get cronjob -n tasks daily-tasks \
      -o jsonpath='{.spec.jobTemplate.spec.template.spec.containers[0].image}'
    echo ""
fi
echo ""

# 测试模式
if [ "$TEST_MODE" == "true" ]; then
    echo "========== 立即测试（手动触发） =========="

    TIMESTAMP=$(date +%Y%m%d%H%M%S)
    TEST_JOB="offline-test-${TIMESTAMP}"

    echo "创建测试Job: ${TEST_JOB}"
    kubectl create job -n tasks ${TEST_JOB} \
      --from=cronjob/device-offline-monitor

    echo ""
    echo "等待Job启动..."
    sleep 3

    echo ""
    echo "========== 查看日志 =========="
    kubectl logs -n tasks -l job-name=${TEST_JOB} -f

    echo ""
    echo "========== 清理测试Job =========="
    kubectl delete job -n tasks ${TEST_JOB}
    echo -e "${GREEN}✅ 测试Job已清理${NC}"
fi

echo ""
echo "=========================================="
echo -e "${GREEN}✅ 镜像更新完成！${NC}"
echo "=========================================="
echo ""
echo "更新摘要："
if [ "$CRONJOB_ONLY" != "true" ]; then
    echo "  ✅ Deployment/python-app 已重启并使用新镜像"
fi
if [ "$DEPLOYMENT_ONLY" != "true" ]; then
    echo "  ✅ CronJob 镜像已更新，将在下次调度时生效："
    echo "     - device-offline-monitor: 每15分钟"
    echo "     - daily-tasks: 每天02:00"
fi
echo ""
echo "后续操作："
if [ "$DEPLOYMENT_ONLY" != "true" ]; then
    echo "1. 验证CronJob更新（立即测试）："
    echo "   kubectl create job test-\$(date +%s) --from=cronjob/device-offline-monitor -n tasks"
    echo "   kubectl logs -n tasks -l app=device-offline-monitor --tail=50"
    echo ""
fi
if [ "$CRONJOB_ONLY" != "true" ]; then
    echo "2. 验证Web服务："
    echo "   kubectl get pods -n default -l app=python-app"
    echo "   curl http://<service-ip>:8000/api/v1/system/health"
    echo ""
fi
echo "3. 查看所有资源状态："
echo "   kubectl get deploy,cronjob -A | grep python-app"
echo ""
